<template>
	<view>
		<view class="content">
			<view class="logo u-flex"><image :src="$u.$assets.logo" mode="widthFix"></image></view>
			<view class="name">{{ name }}</view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="summary"><text>如需正常使用小程序的功能，请点击下方授权登录按钮，打开授权弹窗，并点击允许。</text></view>
			<view class="btn">
				<u-button type="primary" open-type="getPhoneNumber"  size="default" shape="circle" @getphonenumber="getphonenumber">手机号一键登录</u-button>
			</view>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
// import { name, logo } from '@/libs/common/settings'
export default {
	data() {
		return {
			name: '',
			logo: ''
		}
	},
	methods: {
		// 1.获取手机号
		async getphonenumber(e){
			if(e.detail.code){
				uni.showLoading({ title: '登录中...' })
				this.$u.request('user.wxgetphonenumber', { code: e.detail.code })
				.then(res => {
					if(res.user_one == 1){
						this.wxLogin(res.data.id, res.token, res.data)
					}else {
						this.successHandler(res.data.id, res.token, res.data)
					}
					
				}).catch(err => {
					// 取消获取手机号...
					uni.hideLoading()
				})
			}
		},
		// 2.进行微信登录
		async wxLogin(user_id, token, userInfo) {
			const code = await this.getLoginCode()
			const loginInfo = {
				code,
				user_id,
				// token: '',
				// encrypted_data: user.encryptedData,
				// iv: user.iv,
				// raw_data: user.rawData,
				// signature: user.signature
			}
			try{
				const res = await this.$u.request('user.wxappLogin', loginInfo)
				this.successHandler(user_id, token, userInfo)
			}catch(e){
				uni.hideLoading()
				//TODO handle the exception
				console.log(e)
				this.$u.toast('登录失败')
			}
			
		},
		// 登录成功处理
		successHandler(user_id, token, userInfo){
			this.$u.vuex.set('user.userId', user_id)
			this.$u.vuex.set('user.token', token)
			this.$u.vuex.set('user.userInfo', userInfo)
			uni.hideLoading()
			// 获取用户信息
			// this.$u.vuex.dispatch('user/getUserInfo')
			uni.navigateBack({
				delta: 1,
				success() {
					// this.$u.toast('登录成功', 'success')
				}
			})
		},
	
		// 获取小程序用户token
		getLoginCode() {
			return new Promise((reject, resolve) => {
				uni.login({
					provider: 'weixin',
					success: res => {
						reject(res.code)
					},
					fail: () => {
						uni.hideLoading()
						this.$u.toast('授权登录失败，请重新试试')
						resolve()
					}
				})
			}) 
		},
	}
}
</script>

<style lang="scss">
.content {
	margin-top: 200rpx;
	.logo {
		display: flex;
		align-items: center;
		justify-content: center;
		image {
			width: 300rpx;
		}
	}
	.name {
		margin-top: 20rpx;
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		text-align: center;
	}
	.summary {
		justify-content: center;
		margin-top: 40rpx;
		margin-bottom: 60rpx;
		padding: 0 54rpx;
		color: #999;
		line-height: 48rpx;
		font-size: 28rpx;
		text {
			width: 100%;
		}
	}
	.btn {
		padding: 0 100rpx;
	}
}
</style>
